package com.example.kotlinlearningproject.utils

import android.content.Context
import android.media.AudioManager
import android.util.Log

private const val TAG = "AudioUtil"
class AudioUtil(context: Context) {
    private val audioManager: AudioManager = context.getSystemService(Context.AUDIO_SERVICE)
            as AudioManager

    // 调整音量，通过增量进行，正负均可
    fun adjustVolume(increment: Int) {
        val audioStreamType = AudioManager.STREAM_MUSIC // 以媒体音量为例
        audioManager.adjustStreamVolume(audioStreamType, increment, AudioManager.FLAG_SHOW_UI)
    }

    // 获取当前音量
    fun getCurrentVolume(streamType: Int): Int {
        return audioManager.getStreamVolume(streamType)
    }

    // 设置音量，需要考虑到音量的最大和最小值
    fun setVolume(streamType: Int, volume: Int) {
        val maxVolume = audioManager.getStreamMaxVolume(streamType)
        if (volume in 0..maxVolume) {
            audioManager.setStreamVolume(streamType, volume, AudioManager.FLAG_SHOW_UI)
        }
    }

    // 增加音量
    fun increaseVolume() {
        adjustVolume(AudioManager.ADJUST_RAISE)
    }

    // 减少音量
    fun decreaseVolume() {
        adjustVolume(AudioManager.ADJUST_LOWER)
    }

    // 静音
    fun mute() {
        setVolume(AudioManager.STREAM_MUSIC, 0)
    }

    // 最大音量
    fun setMaxVolume() {
        val type = AudioManager.STREAM_MUSIC
        val maxVolume = audioManager.getStreamMaxVolume(type)
        setVolume(type, maxVolume)
    }

    // 最大音量设置，不显示音量控制条
    fun setMaxVolumeSilent() {
        val type = AudioManager.STREAM_MUSIC
        val maxVolume = audioManager.getStreamMaxVolume(type)
        audioManager.setStreamVolume(type, maxVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE)
    }

    // 切换到扬声器播放
    fun changeToSpeaker() {
        audioManager.mode = AudioManager.MODE_IN_COMMUNICATION
//        audioManager.stopBluetoothSco()
//        audioManager.isBluetoothScoOn = false
        Log.e(TAG,"changeToSpeaker")
        audioManager.isSpeakerphoneOn = true
//        setMaxVolumeSilent()
    }
}